/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.asiainfo.utils.sql.sqlbuilder.update;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;

import com.asiainfo.utils.sql.sqlbuilder.IllegalQueryException;

public class UpdateQuery {
	private String table;
	private Map<String, String> sets;
	private Collection<String> wheres;

	public UpdateQuery(String table) {
		this.table = table;

		this.sets = new LinkedHashMap();
		this.wheres = new LinkedList();
	}

	public UpdateQuery set(String column, String value) {
		this.sets.put(column, value);
		return this;
	}

	public UpdateQuery addWhere(String where) {
		this.wheres.add(where);
		return this;
	}

	public String toString() {
		if (this.sets.isEmpty())
			throw new IllegalQueryException("Not contains SET statements!");

		StringBuilder result = new StringBuilder();

		result.append("UPDATE ").append(this.table).append(" SET ");

		for (Map.Entry entry : this.sets.entrySet()) {
			result.append((String) entry.getKey()).append(" = ").append("'").append((String) entry.getValue())
					.append("'");
		}

		if (!(this.wheres.isEmpty())) {
			result.append(" WHERE ");
			result.append(StringUtils.join(this.wheres, " AND "));
		}

		return result.toString();
	}
}